<template>
  <div>
    <h4 class="text-center">{{ innterTitle }}</h4>

    <c-table
      v-if="hasFinsih"
      border
      header-row-class-name="mutiple-table-header"
      v-loading="loading"
      :columns="tableColumns"
      :data="tableData"
      :max-height="dialogHeight"
    ></c-table>

    <manage-panel-risk-table
      v-else
      v-loading="loading"
      :max-height="dialogHeight"
      :columns="tableColumns"
      :data="tableData"
      @edit="getData"
    ></manage-panel-risk-table>

    <div class="text-center mt-3" v-if="!hasFinsih">
      <el-button type="primary" class="btn-long" @click="handleReport">上 报</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { reportRiskTableColumns, reportDataAdapter } from '@/credit/views/city/report/reportMixins'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'

import ManagePanelRiskTable from '@/credit/views/city/report/ManagePanelRiskTable'

export default {
  components: {
    ManagePanelRiskTable,
  },
  props: {
    taskReportData: {
      type: Object,
      default: () => ({}),
    },
    reportStatus: String,
  },
  data() {
    return {
      dialogHeight: 300,
      loading: false,
      params: {
        customer_name: '',
      },
      order: {},
      tableName: 'risk_project_report',
      totalCount: 0,
      tableData: [],
      tableColumns: reportRiskTableColumns.filter(item => item.attrs.prop !== 'submit_time'),
    }
  },
  computed: {
    ...mapGetters(['clientId']),
    reportType() {
      return +this.taskReportData.report_set_type
    },
    innterTitle() {
      return this.taskReportData.report_name || ''
    },
    hasFinsih() {
      return +this.reportStatus === 1
    },
  },
  watch: {
    taskReportData: {
      handler: function () {
        this.getData()
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    this.dialogHeight = Math.max(300, window.innerHeight - (this.hasFinsih ? 230 : 260))
  },
  mounted() {},
  methods: {
    async getData() {
      if (!this.taskReportData.task_id) {
        this.tableData = []
        this.totalCount = 0
        return
      }

      this.loading = true
      const [res] = await this.fetchData(this.getParams())
      this.loading = false
      const data = res || {}
      this.totalCount = data.totalCount || 0
      this.tableData = (data.data || []).map(reportDataAdapter)
    },
    getParams() {
      const params = { ...this.params }
      params['orWhere.service_id.eq'] = this.clientId
      params['orWhere.recommend_service.eq'] = this.clientId
      params['orWhere.pro_service.eq'] = this.clientId

      params['is_submit_report.eq'] = this.hasFinsih ? 1 : 0

      // 月报
      const startDate = this.taskReportData.start_date
      if (/^\d{4}-\d{2}/.test(startDate)) {
        const year = startDate.substring(0, 4)
        const month = startDate.substring(5, 7)
        const lastDay = new Date(year, month, 0).getDate()
        params['load_date.gte'] = `${year}-${month}-01`
        params['load_date.lte'] = `${year}-${month}-${lastDay} 23:59:59`
      }

      return params
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order)
      )
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.getParams(),
        dataAdapter: reportDataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
    handleReport() {
      this.$api
        .updateDataBody(
          this.$serviceName,
          'market_project',
          {
            ...this.getParams(),
            'load_beh_status.in': '2,3,4,5',
          },
          {
            is_submit_report: 1,
            submit_time: this.$utils.dateFormat(new Date()),
            task_id: this.taskReportData.task_id,
          }
        )
        .then(res => {
          this.$message.success('上报成功！')
          this.$emit('success', res)
        })
        .catch(() => {
          this.$message.error('上报失败！')
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
